package com.gupao.vip.controller;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by 17082655 on 2019/1/5.
 * restful风格
 */
@RequestMapping("/jdbc")
@RestController 
public class SpringJdbcController {
	private final JdbcTemplate jdbcTemplate;

	@Autowired
	public SpringJdbcController(JdbcTemplate template) {
		this.jdbcTemplate = template;
	}

	@GetMapping
	public List<Map<String, Object>> queryStudents() {
		// 查询所有用户
		String sql = "select * from student";
		return jdbcTemplate.queryForList(sql);
	}

	@GetMapping("/{id}")
	public Student getStudent(@PathVariable Long id) {
		// 根据主键ID查询
		String sql = "select * from student where id = ?";
		return jdbcTemplate.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper<>(Student.class));
	}

	@DeleteMapping("/{id}")
	public int delStudent(@PathVariable Long id) {
		// 根据主键ID删除用户信息
		String sql = "DELETE FROM student WHERE id = ?";
		return jdbcTemplate.update(sql, id);
	}

	@PostMapping
	public int addStudent(@RequestBody Student Student) {
		// 添加用户
		String sql = "insert into student(name, sex) values(?, ?)";
		return jdbcTemplate.update(sql, Student.getName(), Student.getSex());
	}


	@PutMapping("/{id}")
	public int editStudent(@PathVariable Long id, @RequestBody Student Student) {
		// 根据主键ID修改用户信息
		String sql = "UPDATE student SET name = ? ,sex = ? WHERE id = ?";
		return jdbcTemplate.update(sql,  Student.getName(), Student.getSex(), id);
	}
}
